<?php
declare (strict_types=1);

namespace app\common\model;

use think\Model;
use think\model\concern\SoftDelete;

class AdminAdmin extends Model
{
    use SoftDelete;

    // 获取列表
    public static function getList()
    {
        $where = [];
        $limit = input('get.limit');
        if ($search = input('get.username')) {
            $where[] = ['username', 'like', "%" . $search . "%"];
        }
        $list = self::with([
            'get_school' => function ($a) {
                $a->field('id,school_name');
            }
        ])->order('id', 'desc')->where('id', '>', '1')->withoutField('password,token,delete_time')->where($where)->paginate($limit);
        return ['code' => 0, 'data' => $list->items(), 'extend' => ['count' => $list->total(), 'limit' => $limit]];
    }

    public function getSchool()
    {
        return $this->hasOne(SchoolIndex::class, 'id', 'school_id');
    }

    // 获取日志列表
    public static function getLog()
    {
        $where = [];
        $limit = input('get.limit');
        if ($search = input('get.uid')) {
            $where[] = ['uid', '=', $search];
        }
        $list = AdminAdminLog::with('log')->order('id', 'desc')->where($where)->paginate($limit);
        return ['code' => 0, 'data' => $list->items(), 'extend' => ['count' => $list->total(), 'limit' => $limit]];
    }

    // 管理拥有的角色
    public function roles()
    {
        return $this->belongsToMany('AdminRole', 'admin_admin_role', 'role_id', 'admin_id');
    }

    // 获取管理拥有的角色
    public static function getRole($id)
    {
        $admin = self::with('roles')->where('id', $id)->find();
        $roles = AdminRole::select();
        foreach ($roles as $k => $role) {
            if (isset($admin->roles) && !$admin->roles->isEmpty()) {
                foreach ($admin->roles as $v) {
                    if ($role['id'] == $v['id']) {
                        $roles[$k]['own'] = true;
                    }
                }
            }
        }
        return ['admin' => $admin, 'roles' => $roles];
    }

    // 获取用户直接权限
    public static function getPermission($id)
    {
        $admin = self::with('directPermissions')->find($id);
        $permissions = AdminPermission::order('sort', 'asc')->select();
        foreach ($permissions as $permission) {
            foreach ($admin->direct_permissions as $v) {
                if ($permission->id == $v['id']) {
                    $permission->own = true;
                }
            }
        }
        $permissions = get_tree($permissions->toArray());
        return ['admin' => $admin, 'permissions' => $permissions];
    }


    // 管理的直接权限
    public function directPermissions()
    {
        return $this->belongsToMany('AdminPermission', 'admin_admin_permission', 'permission_id', 'admin_id');
    }

    // 用户的所有权限
    public static function permissions($id, $root)
    {
        $admin = self::with(['roles.permissions', 'directPermissions'])->findOrEmpty($id)->toArray();
        $permissions = [];
        //超级管理员缓存所有权限
        if ($admin['id'] == 1) {
            $perms = AdminPermission::order('sort', 'asc')->select()->toArray();
            foreach ($perms as $p) {
                if ($p['status'] == 1) {
                    $permissions[$p['id']] = $p;
                    $permissions[$p['id']]['href'] = is_url($p['href']) ?? $root . $p['href'];
                }
            }
            if (env('APP_DEBUG') == true) {
                $permissions[0] = [
                    "id" => -1,
                    "pid" => 0,
                    "title" => "CRUD",
                    "icon" => "layui-icon layui-icon-util",
                    "href" => $root . "/crud/index",
                    "type" => 1,
                ];
            }
        } else {
            //处理角色权限
            if (isset($admin['roles']) && !empty($admin['roles'])) {
                foreach ($admin['roles'] as $r) {
                    if (isset($r['permissions']) && !empty($r['permissions'])) {
                        foreach ($r['permissions'] as $p) {
                            if ($p['status'] == 1) {
                                $permissions[$p['id']] = $p;
                                $permissions[$p['id']]['href'] = is_url($p['href']) ?? $root . $p['href'];
                            }
                        }
                    }
                }
            }
            //处理直接权限
            if (isset($admin['directPermissions']) && !empty($admin['directPermissions'])) {
                foreach ($admin['directPermissions'] as $p) {
                    if ($p['status'] == 1) {
                        $permissions[$p['id']] = $p;
                        $permissions[$p['id']]['href'] = is_url($p['href']) ?? $root . $p['href'];
                    }
                }
            }
            $key = array_column($permissions, 'sort');
            array_multisort($key, SORT_ASC, $permissions);
        }
        //合并权限为用户的最终权限
        return $permissions;
    }

    /**
     * 工作人员列表
     * @param $school_id
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function getWorkerList($school_id)
    {

        $where[] = ['school_id', '=', $school_id];
        $limit = input('get.limit');
        if ($search = input('get.username')) {
            $where[] = ['username', 'like', "%" . $search . "%"];
        }
        $list = self::with([
            'get_school' => function ($a) {
                $a->field('id,school_name');
            }
        ])->order('id', 'desc')->where('id', '>', '1')->withoutField('password,token,delete_time')->where($where)->paginate($limit);
        $data = $list->items();
        foreach ($data as $k => $v) {
            $role = dataFind('bl_admin_admin_role', ['admin_id' => 2], '*', 'id');
            $data[$k]['role_id'] = $role['role_id']??1;
            $data[$k]['group'] = AdminRole::where('id', $role['role_id']??1)->find();
        }
        return ['code' => 0, 'data' => $data, 'extend' => ['count' => $list->total(), 'limit' => $limit]];
    }

    /**
     * 园长列表
     * @return array
     * @throws \think\db\exception\DbException
     */
    public static function getPrincipalList()
    {
        $role = dataSelect('bl_admin_admin_role', ['role_id' => 2], '*', 'id');
        $limit = input('get.limit');
        $admin_id = [];
        if ($role)
            foreach ($role as $v) {
                $admin_id[] = $v['admin_id'];
            }
        $where = [];
        $admin = session('admin');
        if ($admin['school_id']) {
            $where[] = ["school_id", "=", $admin['school_id']];
        }

        $list = self::with([
            'get_school' => function ($a) {
                $a->field('id,school_name');
            }
        ])->order('id', 'desc')->where('id', '>', '1')->withoutField('password,token,delete_time')->where($where)
            ->whereIn('id', $admin_id)
            ->paginate($limit);
        return ['code' => 0, 'data' => $list->items(), 'extend' => ['count' => $list->total(), 'limit' => $limit]];
    }

    /**
     * 获取老师列表
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function getTeacherList()
    {
        $role = dataSelect('bl_admin_admin_role', [['role_id', 'in', [6, 9]]], '*', 'id');
        $admin_id = [];
        if ($role)
            foreach ($role as $v) {
                $admin_id[] = $v['admin_id'];
            }
        $where = [];
        $admin = session('admin');
        if ($admin['school_id']) {
            $where[] = ["school_id", "=", $admin['school_id']];
        }
        $list = self::order('id', 'desc')->withoutField('password,token,delete_time')->where($where)
            ->whereIn('id', $admin_id)
            ->select();
        return ['code' => 0, 'data' => $list->toArray(), 'extend' => ['count' => $list->count()]];
    }

    public static function getRecruitList()
    {
        $role = dataSelect('bl_admin_admin_role', [['role_id', 'in', [5, 7]]], '*', 'id');
        $admin_id = [];
        if ($role)
            foreach ($role as $v) {
                $admin_id[] = $v['admin_id'];
            }
        $where = [];
        $admin = session('admin');
        if ($admin['school_id']) {
            $where[] = ["school_id", "=", $admin['school_id']];
        }
        $list = self::order('id', 'desc')->withoutField('password,token,delete_time')->where($where)
            ->whereIn('id', $admin_id)
            ->select();
        $count = $list->count();
        if ($list) {
            $data = $list->toArray();
        } else {
            $data = [];
        }
        return ['code' => 0, 'data' => $data, 'extend' => ['count' => $count]];
    }

    /**
     * 财务列表
     * @return array
     * @throws \think\db\exception\DbException
     */
    public static function getFinanceList()
    {
        $role = dataSelect('bl_admin_admin_role', ['role_id' => 4], '*', 'id');
        $limit = input('get.limit');
        $admin_id = [];
        if ($role)
            foreach ($role as $v) {
                $admin_id[] = $v['admin_id'];
            }
        $where = [];
        $admin = session('admin');
        if ($admin['school_id']) {
            $where[] = ["school_id", "=", $admin['school_id']];
        }

        $list = self::with([
            'get_school' => function ($a) {
                $a->field('id,school_name');
            }
        ])->order('id', 'desc')->where('id', '>', '1')->withoutField('password,token,delete_time')->where($where)
            ->whereIn('id', $admin_id)
            ->paginate($limit);
        return ['code' => 0, 'data' => $list->items(), 'extend' => ['count' => $list->total(), 'limit' => $limit]];
    }

    public static function getPurchaseList()
    {
        $role = dataSelect('bl_admin_admin_role', ['role_id' => 3], '*', 'id');
        $limit = input('get.limit');
        $admin_id = [];
        if ($role)
            foreach ($role as $v) {
                $admin_id[] = $v['admin_id'];
            }
        $where = [];
        $admin = session('admin');
        if ($admin['school_id']) {
            $where[] = ["school_id", "=", $admin['school_id']];
        }

        $list = self::with([
            'get_school' => function ($a) {
                $a->field('id,school_name');
            }
        ])->order('id', 'desc')->where('id', '>', '1')->withoutField('password,token,delete_time')->where($where)
            ->whereIn('id', $admin_id)
            ->paginate($limit);
        return ['code' => 0, 'data' => $list->items(), 'extend' => ['count' => $list->total(), 'limit' => $limit]];
    }

}
